package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.AddDrugAdapter;
import com.hxkcloud.patient.beans.AddDrugBean;
import com.hxkcloud.patient.beans.DrugBean;
import com.hxkcloud.patient.beans.DrugsList;
import com.hxkcloud.patient.popup.CalendarPopWindow;
import com.hxkcloud.patient.popup.DoseSelectPopWindow;
import com.hxkcloud.patient.popup.HourMinuteSelectPop;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageUtil;
import com.hxkcloud.patient.utils.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by william_sun on 2016-10-08.
 * Description:添加修改服药记录
 */
public class AddDrugActivity extends BaseActivity implements View.OnClickListener {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_del;

    private RecyclerView rv;

    private TextView tv_date;
    private LinearLayout ll_time1;
    private TextView tv_time1;
    private View view_time1;
    private LinearLayout ll_time2;
    private TextView tv_time2;
    private View view_time2;
    private LinearLayout ll_time3;
    private TextView tv_time3;
    private View view_time3;
    private LinearLayout ll_time4;
    private TextView tv_time4;
    private View view_time4;

    private Button bt_save;

    private DrugsList drugsList;
    private int type = 0;
    private List<DrugBean> drugs;
    private String date;
    private List<String> times;
    private String recordId = "";
    private boolean isModify = false;//新加或修改
    private boolean hasModify = false;//是否有修改

    private AddDrugAdapter adapter;

    private DoseSelectPopWindow doseSelectPop;//剂量选择popup

    private int curDrugIndex = 0;//记录当前操作的药品

    private CalendarPopWindow calendarPop;//选择服用日期

    private HourMinuteSelectPop timeSelectPop;//时间选择pop
    private int curTimeIndex = 0;//记录是点开那个time

    private boolean isDoseInput = false;
    private boolean isDateInput = false;
    private boolean isTimeInput = false;

    //两个按钮
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;
    private int easynotice_func = 0;//0修改后返回  1删除
    private String patientID = "";
    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_ADDTAKEDRUGS_SUCCESS:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datacommitsuccess);
                }
                setResult(RESULT_OK);
                finish();
                break;
            case MessageCode.NETWORKCODE_ADDTAKEDRUGS_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datacommitfail);
                }
                break;
            case MessageCode.NETWORKCODE_DELETETAKEDRUGS_SUCCESS:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datadeletesuccess);
                }
                finish();
                break;
            case MessageCode.NETWORKCODE_DELETETAKEDRUGS_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datadeletefail);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adddrug);
//        patientID = loginInfo.getUserId();
//        Log.i("--->",patientID);


        Intent iGet = getIntent();
        drugsList = (DrugsList) iGet.getSerializableExtra("druglist");
        type = iGet.getIntExtra("type",0);

        if(type == 0)
        {
            //默认服务器的
            drugs = drugsList.getList();

        }else
        {
//            自己添加的
            drugs = drugsList.getListMedInfo();
        }

        if (iGet.hasExtra("date")) {
            date = iGet.getStringExtra("date");
            isModify = true;
            times = iGet.getStringArrayListExtra("times");
            recordId = iGet.getStringExtra("recordid");


        } else {
            isModify = false;
            times = new ArrayList<>();
        }

        initView();
        initPopup();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_del = (TextView) findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.selectdosetime));

        tv_del.setText(getResources().getText(R.string.delete));
        iv_back.setOnClickListener(this);
        tv_del.setOnClickListener(this);

        rv = (RecyclerView) findViewById(R.id.rv_adddrug);
        tv_date = (TextView) findViewById(R.id.tv_adddrug_date);
        ll_time1 = (LinearLayout) findViewById(R.id.ll_adddrug_time1);
        tv_time1 = (TextView) findViewById(R.id.tv_adddrug_time1);
        view_time1 = findViewById(R.id.view_adddrug_time1);
        ll_time2 = (LinearLayout) findViewById(R.id.ll_adddrug_time2);
        tv_time2 = (TextView) findViewById(R.id.tv_adddrug_time2);
        view_time2 = findViewById(R.id.view_adddrug_time2);
        ll_time3 = (LinearLayout) findViewById(R.id.ll_adddrug_time3);
        tv_time3 = (TextView) findViewById(R.id.tv_adddrug_time3);
        view_time3 = findViewById(R.id.view_adddrug_time3);
        ll_time4 = (LinearLayout) findViewById(R.id.ll_adddrug_time4);
        tv_time4 = (TextView) findViewById(R.id.tv_adddrug_time4);
        view_time4 = findViewById(R.id.view_adddrug_time4);

        bt_save = (Button) findViewById(R.id.bt_adddrug_save);

        tv_date.setOnClickListener(this);
        ll_time1.setOnClickListener(this);
        ll_time2.setOnClickListener(this);
        ll_time3.setOnClickListener(this);
        ll_time4.setOnClickListener(this);

        LinearLayout.LayoutParams lp_ll1 = new LinearLayout.LayoutParams(screenWidth / 5, LinearLayout.LayoutParams.WRAP_CONTENT);
        ll_time1.setLayoutParams(lp_ll1);
        LinearLayout.LayoutParams lp_ll2 = new LinearLayout.LayoutParams(screenWidth / 5, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp_ll2.leftMargin = ImageUtil.dip2px(10, mContext);
        ll_time2.setLayoutParams(lp_ll2);
        ll_time3.setLayoutParams(lp_ll2);
        ll_time4.setLayoutParams(lp_ll2);

        bt_save.setOnClickListener(this);
        bt_save.setBackgroundResource(R.drawable.bt_grey);
        bt_save.setEnabled(false);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(mLayoutManager);

        adapter = new AddDrugAdapter(mContext, drugs, new AddDrugAdapter.onDrugDoseClickListener() {
            @Override
            public void onDoseClick(int position) {
                curDrugIndex = position;
                List<DrugBean.DrugDose> doses = drugs.get(position).getDoseList();
                doseSelectPop.show(ll_title, doses, drugs.get(position).getSelectDose());
            }
        });
        rv.setAdapter(adapter);

        if (isModify) {
            isDoseInput = true;
            isDateInput = true;
            isTimeInput = true;
            bt_save.setBackgroundResource(R.drawable.bt_green);
            bt_save.setEnabled(true);

            tv_date.setText(date);
            switch (Math.min(times.size(), 4)) {
                case 4:
                    tv_time4.setText(times.get(3));
                    tv_time4.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                    view_time4.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                case 3:
                    tv_time3.setText(times.get(2));
                    tv_time3.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                    view_time3.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                case 2:
                    tv_time2.setText(times.get(1));
                    tv_time2.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                    view_time2.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                case 1:
                    tv_time1.setText(times.get(0));
                    tv_time1.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                    view_time1.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                    break;
            }

            tv_del.setVisibility(View.VISIBLE);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String nowS = sdf.format(new Date());

            tv_date.setText(nowS.split(" ")[0]);
            date = nowS;

            tv_time1.setText(nowS.split(" ")[1]);
            tv_time1.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
            view_time1.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
            times.add(nowS.split(" ")[1]);

            isDateInput = true;
            isTimeInput = true;

            tv_del.setVisibility(View.INVISIBLE);
        }
    }

    private void initPopup() {
        doseSelectPop = new DoseSelectPopWindow(AddDrugActivity.this, new DoseSelectPopWindow.onDoseSelectListener() {
            @Override
            public void onDoseSelect(int position) {
                doseSelectPop.dismiss();
                if (drugs.get(curDrugIndex).getDoseList().size() == 0 || drugs.get(curDrugIndex).getDoseList() == null) {
                    return;
                }
                DrugBean.DrugDose dose = drugs.get(curDrugIndex).getDoseList().get(position);
                drugs.get(curDrugIndex).setSelectDose(dose.getDoseId());
                adapter.setData(drugs);

                hasModify = true;
                boolean isAllDoseSelect = true;
                for (DrugBean drug : drugs) {
                    if (TextUtils.isEmpty(drug.getSelectDose())) {
                        isAllDoseSelect = false;
                        break;
                    }
                }
                if (isAllDoseSelect) {
                    isDoseInput = true;
                    if (isDateInput && isTimeInput) {
                        bt_save.setBackgroundResource(R.drawable.bt_green);
                        bt_save.setEnabled(true);
                    }
                } else {
                    isDoseInput = false;
                    bt_save.setBackgroundResource(R.drawable.bt_grey);
                    bt_save.setEnabled(false);
                }

            }
        });

        calendarPop = new CalendarPopWindow(this);
        calendarPop.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                tv_date.setText(calendar);//new SimpleDateFormat("yyyy-MM-dd")
                date = calendar;

                hasModify = true;
                isDateInput = true;
                if (isDoseInput && isTimeInput) {
                    bt_save.setBackgroundResource(R.drawable.bt_green);
                    bt_save.setEnabled(true);
                }
            }
        });
        timeSelectPop = new HourMinuteSelectPop(AddDrugActivity.this, new HourMinuteSelectPop.onHourMinuteSelectListener() {
            @Override
            public void onSelect(String time) {
                switch (curTimeIndex) {
                    case 0:
                        tv_time1.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                        view_time1.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                        tv_time1.setText(time);
                        if (times != null && times.size() > 0) {
                            times.set(0, time);
                        } else {
                            times.add(time);
                        }
                        break;
                    case 1:
                        tv_time2.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                        view_time2.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                        tv_time2.setText(time);
//                        times.set(1, time);
                        if (times != null && times.size() > 1) {
                            times.set(1, time);
                        } else {
                            times.add(time);
                        }
                        break;
                    case 2:
                        tv_time3.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                        view_time3.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                        tv_time3.setText(time);
//                        times.set(2, time);
                        if (times != null && times.size() > 2) {
                            times.set(2, time);
                        } else {
                            times.add(time);
                        }
                        break;
                    case 3:
                        tv_time4.setTextColor(ContextCompat.getColor(mContext, R.color.light_green));
                        view_time4.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_green));
                        tv_time4.setText(time);
//                        times.set(3, time);
                        if (times != null && times.size() > 3) {
                            times.set(3, time);
                        } else {
                            times.add(time);
                        }
                        break;
                }

                hasModify = true;
                isTimeInput = true;
                if (isDateInput && isDoseInput) {
                    bt_save.setBackgroundResource(R.drawable.bt_green);
                    bt_save.setEnabled(true);
                }
            }
        });

        //easynotice
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(AddDrugActivity.this);
            }
        });
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if (hasModify) {
                easynotice_func = 0;
                tv_easynotice_title.setText(R.string.recordissave);
                tv_easynotice_cancel.setText(R.string.nosave);
                tv_easynotice_func.setText(R.string.save);
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(this);
            } else {
                finish();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private void setCurrentTimePop(int i) {
        if (i == 1) {
            String[] tvs = tv_time1.getText().toString().trim().split(":");
            int hour = Integer.parseInt(tvs[0]);
            int min = Integer.parseInt(tvs[1]);
            timeSelectPop.setCurrentTime(hour, min);
        } else if (i == 2) {
            String[] tvs = tv_time2.getText().toString().trim().split(":");
            int hour = Integer.parseInt(tvs[0]);
            int min = Integer.parseInt(tvs[1]);
            timeSelectPop.setCurrentTime(hour, min);
        } else if (i == 3) {
            String[] tvs = tv_time3.getText().toString().trim().split(":");
            int hour = Integer.parseInt(tvs[0]);
            int min = Integer.parseInt(tvs[1]);
            timeSelectPop.setCurrentTime(hour, min);
        } else if (i == 4) {
            String[] tvs = tv_time4.getText().toString().trim().split(":");
            int hour = Integer.parseInt(tvs[0]);
            int min = Integer.parseInt(tvs[1]);
            timeSelectPop.setCurrentTime(hour, min);
        } else {
            timeSelectPop.setCurrentTime(0, 0);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                if (hasModify) {
                    easynotice_func = 0;
                    tv_easynotice_title.setText(R.string.recordissave);
                    tv_easynotice_cancel.setText(R.string.nosave);
                    tv_easynotice_func.setText(R.string.save);
                    popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                    BrightnessUtils.lightOff(this);
                } else {
                    finish();
                }
                break;
            case R.id.tv_title_func:
                if (isModify) {
                    easynotice_func = 1;
                    tv_easynotice_title.setText(R.string.deltherecord);
                    tv_easynotice_cancel.setText(R.string.cancel);
                    tv_easynotice_func.setText(R.string.delete);
                    popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                    BrightnessUtils.lightOff(this);
                }
                break;
            case R.id.bt_adddrug_save:
                if (isDoseInput && isDateInput && isTimeInput) {
                    StringUtil.zhugeTrack(mContext, "我的服药记录中选择药品添加时间页面的保存按钮", "我的服药记录中选择药品添加时间页面的保存点击数");

                    List<AddDrugBean> drugList = new ArrayList<>();
                    for (DrugBean drug : drugs) {
                        AddDrugBean add = new AddDrugBean();
                        add.setDoseId(drug.getSelectDose());
                        add.setDrugId(drug.getDrugId());
                        drugList.add(add);
                    }
                    loading();
                    YiJiaHuNetWorkUtils.addTakeDrugs(drugList, date, recordId, times, handler);
                }
                break;
            case R.id.tv_adddrug_date:
                calendarPop.showBottom(ll_title);
                break;
            case R.id.ll_adddrug_time1:
                curTimeIndex = 0;
                timeSelectPop.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                setCurrentTimePop(1);
                BrightnessUtils.lightOff(AddDrugActivity.this);
                break;
            case R.id.ll_adddrug_time2:
                if (times.size() > 0) {
                    curTimeIndex = 1;
                    timeSelectPop.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                    if ("无".equals(tv_time2.getText().toString().trim())) {
                        setCurrentTimePop(5);
                    } else {
                        setCurrentTimePop(2);
                    }
                    BrightnessUtils.lightOff(AddDrugActivity.this);
                }
                break;
            case R.id.ll_adddrug_time3:
                if (times.size() > 1) {
                    curTimeIndex = 2;
                    timeSelectPop.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                    if ("无".equals(tv_time3.getText().toString().trim())) {
                        setCurrentTimePop(5);
                    } else {
                        setCurrentTimePop(3);
                    }
                    BrightnessUtils.lightOff(AddDrugActivity.this);
                }
                break;
            case R.id.ll_adddrug_time4:
                if (times.size() > 2) {
                    curTimeIndex = 3;
                    timeSelectPop.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                    if ("无".equals(tv_time4.getText().toString().trim())) {
                        setCurrentTimePop(5);
                    } else {
                        setCurrentTimePop(4);
                    }
                    BrightnessUtils.lightOff(AddDrugActivity.this);
                }
                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                if (easynotice_func == 0) {
                    finish();
                }
                if (easynotice_func == 1) {

                }
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                if (easynotice_func == 0) {
                    if (isDoseInput && isDateInput && isTimeInput) {
                        List<AddDrugBean> drugList = new ArrayList<>();
                        for (DrugBean drug : drugs) {
                            AddDrugBean add = new AddDrugBean();
                            add.setDoseId(drug.getSelectDose());
                            add.setDrugId(drug.getDrugId());
                            drugList.add(add);
                        }
                        loading();
                        YiJiaHuNetWorkUtils.addTakeDrugs(drugList, date, recordId, times, handler);
                    } else {
                        toastMsg(R.string.pleaseinputwholecontent);
                    }
                }
                if (easynotice_func == 1) {
                    loading();
                    YiJiaHuNetWorkUtils.deleteTakeDrugs(recordId, handler);
                }
                break;
        }
    }
}
